package com.houxy.service.impl;

import com.houxy.repository.model.entity.Department;
import com.houxy.repository.model.entity.Hospital;
import com.houxy.repository.model.entity.Notice;
import com.houxy.service.DepartmentService;
import com.houxy.service.HospitalService;
import com.houxy.service.NoticeService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author Hou
 * @date 2018/03/19 11:29
 * @describe：
 */
@Component
public class InitComponent implements ServletContextListener, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 初始化信息
     *
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();


        //初始化医院
        HospitalService hospitalService = (HospitalService) applicationContext.getBean("hospitalService");
        List<Hospital> hospitalList = hospitalService.findAll();
        servletContext.setAttribute("hospitalList", hospitalList);

        //初始化医院
        DepartmentService departmentService = (DepartmentService) applicationContext.getBean("departmentService");
        List<Department> departmentList = departmentService.findAllDepartment();
        servletContext.setAttribute("departmentList", departmentList);

        //初始化公告
        NoticeService noticeService = (NoticeService) applicationContext.getBean("noticeService");
        List<Notice> noticeList = noticeService.findAllLimit();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");

        noticeList.stream().forEach(notice -> {

            notice.setTime(sdf.format(notice.getCreateTime()));
        });
        servletContext.setAttribute("noticeIndexList", noticeList);


    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
